package com.atguigu.gulimall.cart.Interceptor;

import com.atguigu.common.constan.AuthServerConstant;
import com.atguigu.gulimall.cart.constant.CartConstan;
import com.atguigu.gulimall.cart.vo.MemberVo;
import com.atguigu.gulimall.cart.vo.UserInfoVo;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 拦截器
 */
@Component
public class CatInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoVo> threadlocal = new ThreadLocal<>();

    /**
     * 目标方法前进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求信息
        HttpSession session = request.getSession();
        MemberVo attribute = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        UserInfoVo userInfoVo = new UserInfoVo();
        //判断是否为空
        if (attribute!=null){
           userInfoVo.setId(attribute.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                //判断cookie的值是否和临时购物车的值相等
                if (name.equals(CartConstan.TEMP_COOK_USER_KEY)){
                    userInfoVo.setUserKey(cookie.getValue()); //购物车
                }
            }
        }
        //如果cookie等于空
        if (StringUtils.isEmpty(userInfoVo.getUserKey())){
            String uid = UUID.randomUUID().toString();
            //创建一个临时用户 临时购物车
            userInfoVo.setUserKey(uid);
        }
        threadlocal.set(userInfoVo);
        return true;
    }

    /**
     * 目标方法后进行拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        UserInfoVo userInfoVo = threadlocal.get();
        //创建一个cookie 把临时key存如到cookie 这样用户再次访问是会携带次cookie
        Cookie cookie = new Cookie(CartConstan.TEMP_COOK_USER_KEY,userInfoVo.getUserKey());
        cookie.setMaxAge(CartConstan.TEMP_COOK_USER_TIMEOUT);
        cookie.setPath("127.0.0.1:15000");//作用域
        response.addCookie(cookie);
    }
}
